<template>
  <section class='f-withdraw-list'>
    <ul class="f-search">
      <li class="g-flex-ct" style="width:180px" @click="openDatePicker()">
        <p class="f-mr-05">{{currentDateStr}}</p>
        <van-icon style="margin-top:2px" name="arrow-down" />
      </li>
      <li class="g-flex-ct" @click="openPicker(1)">
        <p class="f-mr-05">{{searchForm.orderStatusName || '全部状态'}}</p>
        <van-icon style="margin-top:2px" name="arrow-down" />
      </li>
      <li class="g-flex-ct f-ml-20" @click="openPicker(2)">
        <p class="f-mr-05">{{searchForm.payTypeName || '全部方式'}}</p>
        <van-icon style="margin-top:2px" name="arrow-down" />
      </li>
    </ul>

    <section class="f-card">
      <p style="font-weight: 400;font-size: 9px;color: #424242;">已提现(元)</p>
      <p class="f-mt-10" style="font-weight: 500;font-size: 20px;color: #000000;">{{toThousands(incomeStatics.totalMoney)}}</p>
    </section>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :style="{ height: currentHeight }" style="overflow-y: auto;">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <section class="f-cell-group" v-for="(item,index) in tableData" :key="index">
          <p v-if="index == 0 || getDateTime(item.createTime)[3] != getDateTime(tableData[index-1]?.createTime)[3]" class="f-date"
            :style="{'margin-top': index == 0? '0': '18px'}">
            {{getDateTime(item.createTime)[0]}}年{{getDateTime(item.createTime)[1]}}月
          </p>
          <p class="f-divider" v-if="getDateTime(item.createTime)[3] == getDateTime(tableData[index-1]?.createTime)[3]"></p>
          <div class="f-cell" @click="pageJump('withdraw/detail',item)">
            <div class="g-flex-ct">
              <img v-if="item.payType == 2" style="width:35px;height:35px;margin-left:17px"
                src="../../../assets/icons/withdraw_icon_wx.png" alt="">
              <img v-if="item.payType == 3" style="width:35px;height:35px;margin-left:17px"
                src="../../../assets/icons/withdraw_icon_zfb.png" alt="">
              <img v-if="item.payType == 11" style="width:35px;height:35px;margin-left:17px"
                src="../../../assets/icons/withdraw_icon_yhk.png" alt="">
              <div class="f-ml-10">
                <p style="font-weight: 500;font-size: 12px;color: #000000;">
                  {{item.payType == 2? '微信': item.payType == 3? '支付宝': '银行卡'}}提现{{toThousands(item.totalMoney)}}元</p>
                <p class="f-mt-05" style="font-weight: 300;font-size: 12px;">{{getDateTime(item.createTime)[6]}}
                </p>
              </div>
            </div>
            <p class="f-mr-15" style="font-weight: 300;font-size: 12px;" :style="{color: orderStatusColor[item.orderStatus]}">
              {{orderStatus[item.orderStatus]}}
            </p>
          </div>
        </section>
      </van-list>
    </van-pull-refresh>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">选择{{pickerTitle}}</p>
      <van-picker ref="pickerRef" v-model="searchForm.selectId" :columns="columns" :columns-field-names="customFieldName"
        :show-toolbar="false" />

      <div class="f-popup-btn">
        <van-button block type="primary" @click="handlePicker()">确定</van-button>
      </div>
    </van-popup>

    <Date-Picker ref="datePickerRef" type='time' @selectDate="selectDate"></Date-Picker>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { toThousands, getUnixTime, initDatepicker, getDateTime } from '../../../utils/utils';
import DatePicker from '../../../components/DatePicker.vue'
import api from '../api'

export default {
  components: { DatePicker },

  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const pickerRef = ref()
    const datePickerRef = ref()

    const state = reactive({
      searchForm: {
        "orderBy": "id desc",
        "orderStatus": "",
        "payType": '',
        "shopName": "",
        "page": 1,
        "size": 10,
        "sysOrderId": "",
        "timeMax": '',
        "timeMin": ''
      },
      currentDateStr: "",

      loading: false,
      finished: false,
      refreshing: false,
      tableData: [],
      total: 0,
      currentHeight: '740px',

      pickerTitle: '',
      showPicker: false,
      columns: [],
      customFieldName: {
        text: 'text',
        value: 'value',
        children: 'children'
      },

      orderStatus: {
        '1': '提现中',
        '2': '已关闭',
        '3': '失败',
        '4': '成功',
        '5': '待人工处理',
      },
      orderStatusColor: {
        '1': '#488BFE',
        '2': '#FF2B2B',
        '3': '#FF2B2B',
        '4': '#1FBE2A',
      },
      incomeStatics: {}
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '提现记录',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
      });

      state.currentHeight = window.innerHeight - 230 + 'px'

      state.searchForm.timeMin = initDatepicker(4, 3 * 30 * 24 * 60 * 60 * 1000);
      state.searchForm.timeMax = initDatepicker(3);
      let str = getDateTime(state.searchForm.timeMin)[8] + ' 至 ' + getDateTime(state.searchForm.timeMax)[8]
      state.currentDateStr = str
    })

    const onLoad = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))

      if (state.refreshing) {
        state.tableData = [];
        state.refreshing = false;
      }

      api.incomeWithdrawList(json).then(res => {
        state.refreshing = false

        if (res.data.list.length) state.searchForm.page += 1
        state.tableData.push(...res.data.list)
        getIncomeWithdrawStatics()

        // 防止触发两次
        if (state.tableData.length >= res.data.total) {
          state.finished = true;
        } else {
          state.finished = false;
        }

        // 加载状态结束
        state.loading = false;

        // 数据全部加载完成
        if (state.tableData.length < 10) {
          state.finished = true;
        }
      }).catch(err => {
        state.loading = false;
        state.finished = true;
        state.refreshing = false
      })
    };

    const onRefresh = () => {
      state.searchForm.page = 1

      // 清空列表数据
      state.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      state.loading = true;
      onLoad();
    };

    const getIncomeWithdrawStatics = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))
      api.incomeWithdrawStatics(json).then(res => {
        state.incomeStatics = res.data
      })
    }

    const openDatePicker = () => {
      datePickerRef.value.datePopup = true
    }

    const selectDate = (e) => {
      let str = e.startStr + ' 至 ' + e.endStr
      state.currentDateStr = str
      state.searchForm.timeMin = getUnixTime(e.startStr)
      state.searchForm.timeMax = getUnixTime(e.endStr) - 999 + 24 * 60 * 60 * 1000;
      state.refreshing = true
      onRefresh()
    }

    const openPicker = (e) => {
      if (e == 1) {
        state.pickerTitle = '全部状态'
        state.columns = [
          { text: '全部', value: '' },
          { text: '提现中', value: '1' },
          { text: '已关闭', value: '2' },
          { text: '失败', value: '3' },
          { text: '成功', value: '4' },
        ]
      } else if (e == 2) {
        state.pickerTitle = '全部方式'
        state.columns = [
          { text: '全部', value: '' },
          { text: '微信', value: '2' },
          { text: '支付宝', value: '3' },
        ]
      }
      state.showPicker = true
    }

    const handlePicker = (e) => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      state.showPicker = false
      state.refreshing = true
      if (state.pickerTitle == '全部状态') {
        state.searchForm.orderStatus = data.value
        state.searchForm.orderStatusName = data.text == '全部' ? '' : data.text
      }
      if (state.pickerTitle == '全部方式') {
        state.searchForm.payType = data.value
        state.searchForm.payTypeName = data.text == '全部' ? '' : data.text
      }

      onRefresh()
    }

    const pageJump = (name, params) => {
      router.push({
        path: `/capital/${name}`,
        query: {
          sysOrderId: params.sysOrderId
        }
      })
    }

    return {
      ...toRefs(state),
      getDateTime,
      toThousands,
      pickerRef,
      datePickerRef,
      onLoad,
      onRefresh,
      openDatePicker,
      selectDate,
      openPicker,
      handlePicker,
      pageJump
    }
  }
}
</script>

<style lang='scss' scoped>
.f-withdraw-list {
  .f-search {
    font-size: 12px;
    font-weight: 300;
    color: #000000;
    padding: 8px 5px 14px 16px;
    display: flex;
    align-items: center;
  }
  .f-card {
    width: 343px;
    background: #ffffff;
    margin: 0 16px;
    text-align: center;
    padding-top: 13px;
    padding-bottom: 10px;
    margin-bottom: 18px;
  }
  .f-cell-group {
    .f-date {
      font-weight: 400;
      font-size: 12px;
      color: #000000;
      margin: 0px 0 8px 17px;
    }
    .f-cell {
      background: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 0;
    }
    .f-divider {
      width: 100%;
      height: 1px;
      margin-left: 12px;
      border-bottom: 1px solid #dddddd;
    }
  }
}
</style>